package Myresponse;


import Man.UserMapper;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/Tom/loginServlet")

public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username=req.getParameter("username");
    String password=req.getParameter("password");

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionfactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession=sqlSessionfactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user=userMapper.selcet(username,password);
        sqlSession.close();

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer=resp.getWriter();
        String remember=req.getParameter("remember");
        if(user!=null){
            if ("1".equals(remember)){
                Cookie username1=new Cookie("username",username);
                Cookie password1=new Cookie("password",password);
                password1.setMaxAge(60*60*24*7);
                username1.setMaxAge(60*60*24*7);
                resp.addCookie(username1);
                resp.addCookie(password1);
            }

            String con=req.getContextPath();
            resp.sendRedirect(con+"/R-C.jpg");

        }else{
            writer.write("登陆失败");
        }

}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
